package com.yixin.utils;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectResult;
import com.yixin.entity.AliyunOSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Component
public class AliyunOSSOperator {
    @Autowired
    private AliyunOSSProperties aliyunOSSProperties;

    public String upload(String fileName, byte[] bytes) throws Exception {
        // 从环境变量中读取阿里云账号信息
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 获取当前系统日期的字符串，格式为yyyyMM
        String dir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM"));
        // 生成一个新的不重复的文件名
        String newFileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        // 确保使用正斜杠作为路径分隔符
        String filePath = dir + "/" + newFileName;

        // 创建OSSClient实例
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(aliyunOSSProperties.getEndpoint())
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(aliyunOSSProperties.getRegion())
                .build();

        try {
            // 使用 ByteArrayInputStream 替代 File 对象，避免本地文件路径问题
            PutObjectResult result = ossClient.putObject(aliyunOSSProperties.getBucketName(), filePath, new ByteArrayInputStream(bytes));
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return aliyunOSSProperties.getEndpoint().split("//")[0] + aliyunOSSProperties.getBucketName() + "." + aliyunOSSProperties.getEndpoint().split("//")[1] + "/" + filePath;
    }

}
